package com.semidata.trp.monitor.http;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpRequest;

import com.semidata.rtd.core.http.server.AbstractDispatchHandler;
import com.semidata.rtd.core.http.server.DefaultDispatcher;
import com.semidata.rtd.core.http.server.HttpDispatchHandler;
import com.semidata.rtd.core.http.server.HttpSession;
import com.semidata.rtd.core.http.server.UrlMatcher;
import com.semidata.rtd.core.log.Logger;
import com.semidata.trp.monitor.config.Config;
import com.semidata.trp.monitor.job.MonitorJob;

public class MonitorHttpDispatcher extends DefaultDispatcher {

    public MonitorHttpDispatcher() {
        super();

        final Config config = Config.getConfig();

        addUrlMatcher(new UrlMatcher("") {

            @Override
            protected boolean match(HttpRequest request) {
                String requestUrl = request.getUri();
                int pos = requestUrl.indexOf("?");
                if (pos != -1)
                    requestUrl = requestUrl.substring(0, pos);
                if (!requestUrl.endsWith("/"))
                    requestUrl = requestUrl.concat("/");
               
                return requestUrl.equals(config.getImpressionPrefix()) || requestUrl.equals(config.getClickPrefix());
            }
            
            @Override
            protected HttpDispatchHandler createHandler(ChannelHandlerContext ctx, HttpRequest request) {
                return new AbstractDispatchHandler(ctx, request) {
                    @Override
                    public void handle(HttpSession session) {
                    	Logger.log("INFO", "start http handler , job run");
                        MonitorJob job = new MonitorJob(session);
                        job.run();
                    }
                };
            }
        });
    }

}
